#!/bin/bash
# create, edit and view week log
# usage: weeklog OPTIONS
# example: weeklog // create, edit and view the log of this week
#          weeklog "last week" // create, edit and view the log of last week
#          weeklog "2 weeks ago" // create, edit and view the log of tomorrow

if [ ! -f ~/.calendar ]; then
  echo -ne "calendar_path="
  read calendar_path
  echo -ne "version_control=(none, svn, git, cvs)"
  read version_control
  echo "calendar_path=$calendar_path" >> ~/.calendar
  echo "version_control=$version_control" >> ~/.calendar
else
  while read line; do
    case $line in
      "calendar_path="*) calendar_path=${line##calendar_path=};;
      "version_control="*) version_control=${line##version_control=};;
    esac
  done < ~/.calendar
fi

cd $calendar_path
if [ "$version_control" = "svn" ]; then
  svn up
fi

if [ $# -eq 0 ]; then
  dayname="this week"
else
  if [ "$1" = "update" ]; then
    if [ "$version_control" = "svn" ]; then
      svn update
    fi
    exit
  else
    if [ "$1" = "up" ]; then
      if [ "$version_control" = "svn" ]; then
        svn up
      fi
      exit
    else
      dayname=$1
    fi
  fi
fi

# 86400 is the number of seconds per day (86400=60*60*24)
dayofweek=`date --date "$dayname" +%u`
monday=`date --date @$(($(date --date "$dayname" +%s)-($dayofweek-1)*86400)) +%F`
sunday=`date --date @$(($(date --date "$dayname" +%s)+(7-$dayofweek)*86400)) +%F`
logfilename="`date --date="$monday" +%F`--`date --date="$sunday" +%F`";

if [ -f $logfilename ]; then
  vim $logfilename 
  if [ "$version_control" = "svn" ]; then
    svn commit -m "update $logfilename"
  fi
else
  echo $logfilename >> $logfilename
  vim $logfilename
  if [ "$version_control" = "svn" ]; then
    svn add $logfilename
    svn commit -m "add $logfilename"
  fi
fi
